package arrray;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author huangxianjin
 * @date 2025/8/29 21:32
 * @description "反转字符串中的单词"
 */
public class LC_151 {
    public static void main(String[] args) {
        LC_151 lc = new LC_151();
        String s = "a good   example";
        String[] split = s.split(" ");
//        lc.reverseWords(s);
//        for (int i = 0; i < split.length; i++) {
//            System.out.println(split[i]);
//            System.out.println(split[i].length());
//        }
    }

    //自己的做法
    public String reverseWords(String s) {
        //去除首位空格
        String str = s.trim();
        String[] arr = str.split(" ");//字符串中的空格会返回空串而不是空格
        String res = "";
        for (int i = arr.length - 1; i >= 0; i--) {
            if (!arr[i].isEmpty()) {
                if (i == 0) {
                    res += arr[i];
                } else {
                    res += arr[i] + " ";
                    System.out.println(res.length());
                }
            }
        }
        return res;
    }

    //官方做法
    public String reverseWords2(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);
    }
}
